package com.zjun.initialize;

import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;

import static com.zjun.config.WebAutoConfiguration.INITIALIZE_PATH;

/**
 * 初始化DispatcherServlet
 * DispatcherServlet（Spring MVC核心调度器）默认采用懒加载机制，只有在收到第一个HTTP请求时才会完全初始化，所以在应用启动后，直接模拟一个请求提前加载。
 */
@RequiredArgsConstructor
public class InitializeDispatcherServletHandler implements CommandLineRunner {
    private final RestTemplate restTemplate;

    private final ConfigurableEnvironment configurableEnvironment;

    @Override
    public void run(String... args) throws Exception {
        String url = String.format("http://127.0.0.1:%s%s",
                configurableEnvironment.getProperty("server.port", "8080") + configurableEnvironment.getProperty("server.servlet.context-path", ""),
                INITIALIZE_PATH);
        try {
            restTemplate.execute(url, HttpMethod.GET, null, null);
        } catch (Throwable ignored) {
        }
    }
}
